package com.example.demo.mq;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by Hy on 2019/3/13.
 */
public class Receiver {
    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        Connection connection =null;
        Session session =null;
        Destination destination =null;
        MessageConsumer consumer =null;
        connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,"tcp://localhost:61616");
        try {
           connection = connectionFactory.createConnection();
           connection.start();
           session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
           destination = session.createQueue("FirstQueue");
           consumer = session.createConsumer(destination);
           while(true){
               TextMessage message = (TextMessage) consumer.receive(100);
               if(null!=message){
                   System.out.println("收到消息===="+message.getText());
               }else{
                   break;
               }
           }
        }catch(Exception e){
           e.printStackTrace();
        }finally{
            try{
                if(consumer!=null){
                    consumer.close();
                }
            }catch(Throwable ignore){}
          try{
              if(session!=null){
                  session.close();
              }
          }catch(Throwable ignore){}
            try{
                if(connection!=null){
                    connection.close();
                }
            }catch(Throwable ignore){}
        }
    }
}
